#!/usr/bin/env python3
# usage: python3 get_img_from_video.py mediafile [frame_num] [output_file] [threshold_type] [threshold] [max_value] [crop_info]
import cv2
import sys


try:
    mediafile = sys.argv[1]
except:
    mediafile = 'test.mp4'

media = cv2.VideoCapture(mediafile)
frames = int(media.get(cv2.CAP_PROP_FRAME_COUNT))
_,image = media.read()
imageHeight,imageWidth,_channels = image.shape

try:
    frame_num = int(sys.argv[2])
except:
    frame_num = 1

media = cv2.VideoCapture(mediafile)

try:
    threshold_type = int(sys.argv[4])
except:
    threshold_type = 0

if threshold_type == 0:
    thresholdType = cv2.THRESH_BINARY
elif threshold_type == 1:
    thresholdType = cv2.THRESH_BINARY_INV
elif threshold_type == 2:
    thresholdType = cv2.THRESH_TRUNC
elif threshold_type == 3:
    thresholdType = cv2.THRESH_TOZERO
elif threshold_type == 4:
    thresholdType = cv2.THRESH_TOZERO_INV
elif threshold_type == 7:
    thresholdType = cv2.THRESH_MASK
elif threshold_type == 16:
    thresholdType = cv2.THRESH_TRIANGLE

print("threshold_type is:\t{}".format(threshold_type))
n = 0
while n <= frames:
    _,img = media.read()
    n += 1
    if n==frame_num:
        mean,stddv = cv2.meanStdDev(img)
        imgMean = sum(mean)/_channels
        imgStddv = sum(stddv)
        print("{mean}\t{stddv}".format(mean=imgMean,stddv=imgStddv))

        try:
            threshold = int(sys.argv[5])
        except:
            threshold = int(imgMean)
        try:
            max_value = sys.argv[6]
        except:
            max_value = 255
            max_value = imgMean + imgStddv

        try:
            crop_info = sys.argv[7]
        except:
            crop_info = ''.join(['0:',str(imageHeight),',0:',str(imageWidth)])

        row_info,col_info = crop_info.split(',')
        start_row,end_row = row_info.split(':')
        start_col,end_col = col_info.split(':')

        try:
            output_file = sys.argv[3]
        except:
            output_file = ''.join([mediafile.split('/')[-1].split('.')[0],'_',str(frame_num),'_',str(int(end_row)-int(start_row)),'x',str(int(end_col)-int(start_col)),'.jpg'])

        _,img = cv2.threshold(img,threshold,max_value,threshold_type)
        croped_img = img[int(start_row):int(end_row),int(start_col):int(end_col)]
        cv2.imwrite(output_file,croped_img)
        break

